﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using NPOI.SS.Formula.Functions;
using Warehouse.API.Applcation.Command.InjureCommand;
using Warehouse.Domain;
using Warehouse.Infrstructre;
using Warehouse.Infrstructre.Interface;

namespace Warehouse.API.Applcation.CommandHandlers.InjureCommandHandler
{
    public class InjureUpdCommandHandler : IRequestHandler<InjureUpdCommand, int>
    {
        IInjureRepository IRep;
        EFCoreDBcontext dbContext;
        IInProductRepository ipRep;

        public InjureUpdCommandHandler(IInjureRepository IRep,
        EFCoreDBcontext dbContext,
        IInProductRepository ipRep)
        {
            this.IRep = IRep;
            this.dbContext = dbContext;
            this.ipRep = ipRep;
        }

        public async Task<int> Handle(InjureUpdCommand request, CancellationToken cancellationToken)
        {
            using (var tran = await dbContext.Database.BeginTransactionAsync((System.Data.IsolationLevel.Serializable)))
            {

                try
                {
                    //修改报损信息
                    var se = await IRep.GetModelAsync(request.addDto.InjureId);
                    se.InjureId = request.addDto.InjureId;
                    se.InjureCode = request.addDto.InjureCode;
                    se.MorderNumber = request.addDto.MorderNumber;
                    se.MakePerson = request.addDto.MakePerson;
                    se.MarkTime = request.addDto.MarkTime;
                    se.office_id = request.addDto.office_id;
                    se.user_id = request.addDto.user_id;
                    await IRep.UpdateAsync(se);

                    //删除报损表中的数据
                    var res = (await ipRep.GetAsync(c => c.InjureCode == se.InjureCode)).ToList();
                    foreach (var item in res)
                    {
                        await ipRep.RemoveAsync(item);
                    }

                    //重新添加报损产品的数据

                    foreach (var item in request.addDto.injureDetails)
                    {
                        InProduct list = new InProduct();
                        list.AuditStart = 1;
                        list.InjureCode = se.InjureCode;
                        list.ProductId = item.ProductId;
                        list.StorehouseId = item.StorehouseId;
                        list.InjureNum = item.InjureNum;
                        list.office_id = item.office_id;
                        list.user_id = item.user_id;
                        await ipRep.AddAsync(list);
                    }

                    // 提交事务
                    tran.Commit();

                    return 1;  // 返回最终的结果
                }
                catch (Exception)
                {
                    // 回滚事务
                    tran.Rollback();
                    throw;
                }
            
            }
        }
    }
}
